<template>
  <a-layout-content class="chat-panel">
    <a-layout-header class="chat-header">
      <span class="chat-title">
        {{ localGroupInfo.name }}
        <span class="member-count">({{ memberCount }}人)</span>
      </span>
      <div class="chat-groupInfo">
        <EllipsisOutlined
          class="toolbar-icon"
          @click="showDrawerWithGroupInfo"
        />
      </div>
    </a-layout-header>

    <a-drawer
      v-model:open="openGroupInfo"
      title="群聊资料"
      placement="right"
      width="300"
    >
      <div class="group-info-container">
        <div class="group-basic-info">
          <div class="group-avatar">
            <a-avatar
              :size="80"
              :src="
                localGroupInfo.avatar || '@/assets/images/group-default.png'
              "
            />
          </div>
          <h3>{{ localGroupInfo.name }}</h3>
          <p class="group-id">群号：{{ localGroupInfo.id }}</p>
        </div>

        <a-divider />

        <div class="group-announcement">
          <h4>群公告</h4>
          <p>{{ localGroupInfo.announcement || "暂无公告" }}</p>
        </div>

        <a-divider />

        <div class="group-members">
          <div class="members-header">
            <h4>群成员 ({{ memberCount }})</h4>
            <a-button type="link">查看更多</a-button>
          </div>
          <div class="members-list">
            <div
              v-for="member in Array.from(groupMembers.values()).slice(0, 10)"
              :key="member.userId"
              class="member-item"
            >
              <a-dropdown
                :trigger="['click']"
                @visibleChange="
                  (visible) =>
                    handleMemberContextMenuVisibleChange(visible, member)
                "
              >
                <div class="member-content">
                  <a-avatar :src="member.avatar" />
                  <span>{{ member.nickname }}</span>
                </div>
                <template #overlay>
                  <a-menu @click="handleMemberMenuClick">
                    <a-menu-item key="profile">
                      <UserOutlined /> 查看资料
                    </a-menu-item>
                    <a-menu-item key="muteORunmute" v-if="isGroupAdmin">
                      <StopOutlined />
                      {{ member.status === 1 ? "禁言" : "解除禁言" }}
                    </a-menu-item>
                    <a-menu-item key="remove" v-if="isGroupAdmin" danger>
                      <DeleteOutlined /> 移出群聊
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </div>
            <div class="member-item add-member">
              <a-button type="dashed" shape="circle" icon="plus" />
              <span>邀请</span>
            </div>
          </div>
        </div>

        <a-divider />

        <div class="group-actions">
          <template v-if="isGroupOwner">
            <a-button block class="action-btn" @click="showModifyGroupInfo">
              修改群资料
            </a-button>
            <a-button
              block
              class="action-btn"
              type="primary"
              danger
              @click="dissolveGroup"
            >
              解散群聊
            </a-button>
          </template>
          <template v-else>
            <a-button block class="action-btn" @click="showModifyNickname">
              修改群内昵称
            </a-button>
            <a-button
              block
              class="action-btn"
              type="primary"
              danger
              @click="quitGroup"
            >
              退出群聊
            </a-button>
          </template>
        </div>
      </div>
    </a-drawer>

    <!-- 修改群资料弹窗 -->
    <a-modal
      v-model:visible="modifyGroupInfoVisible"
      title="修改群资料"
      :footer="null"
      width="600px"
      @cancel="handleModifyGroupInfoCancel"
    >
      <div class="modify-group-info">
        <div class="group-avatar-section">
          <a-upload
            name="avatar"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :before-upload="beforeAvatarUpload"
            @change="handleAvatarChange"
          >
            <img
              v-if="groupInfoForm.avatar"
              :src="groupInfoForm.avatar"
              alt="avatar"
            />
            <div v-else>
              <plus-outlined />
              <div style="margin-top: 8px">上传头像</div>
            </div>
          </a-upload>
        </div>
        <div class="group-form-section">
          <a-form
            :model="groupInfoForm"
            :rules="groupInfoRules"
            ref="groupInfoFormRef"
            layout="vertical"
          >
            <a-form-item label="群称" name="name">
              <a-input
                v-model:value="groupInfoForm.name"
                placeholder="请输入群名称"
              />
            </a-form-item>
            <a-form-item label="群描述" name="description">
              <a-textarea
                v-model:value="groupInfoForm.description"
                placeholder="请输入群描述"
                :rows="4"
              />
            </a-form-item>
            <a-form-item label="群公告" name="announcement">
              <a-textarea
                v-model:value="groupInfoForm.announcement"
                placeholder="请输入群公告"
                :rows="4"
              />
            </a-form-item>
            <a-form-item>
              <div class="form-buttons">
                <a-button @click="handleModifyGroupInfoCancel">取消</a-button>
                <a-button type="primary" @click="handleModifyGroupInfoSubmit">
                  保存
                </a-button>
              </div>
            </a-form-item>
          </a-form>
        </div>
      </div>
    </a-modal>

    <!-- 修改群昵称弹窗 -->
    <a-modal
      v-model:visible="modifyNicknameVisible"
      title="修改群内昵称"
      @ok="handleModifyNicknameSubmit"
      @cancel="modifyNicknameVisible = false"
    >
      <a-form :model="nicknameForm" layout="vertical">
        <a-form-item label="群内昵称" name="nickname">
          <a-input
            v-model:value="nicknameForm.nickname"
            placeholder="请输入新的群内昵称"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <div class="chat-messages" ref="messagesContainer">
      <div
        v-for="(message, index) in messages"
        :key="index"
        class="message"
        :class="{ 'message-self': message.senderId === currentUserId }"
      >
        <a-avatar :src="getSenderAvatar(message.senderId)" />
        <div class="message-wrapper">
          <div class="message-sender" v-if="message.senderId !== currentUserId">
            {{ getSenderName(message.senderId) }}
          </div>
          <div class="message-content" v-html="renderMessage(message)"></div>
          <div class="message-time">{{ formatTime(message.createTime) }}</div>
        </div>
      </div>
    </div>

    <div class="chat-input-area">
      <div class="chat-toolbar">
        <EmojiPicker @select="insertEmoji" />
        <paper-clip-outlined class="toolbar-icon" @click="handleFileClick" />
        <input
          type="file"
          ref="fileInput"
          style="display: none"
          @change="handleFileSelect"
        />
        <picture-outlined class="toolbar-icon" />
      </div>

      <a-textarea
        v-model:value="inputMessage"
        :rows="4"
        placeholder="输入消息..."
        class="chat-input"
        @keyup.enter.exact="sendMessage"
      />
      <a-button type="primary" class="send-button" @click="sendMessage">
        发送
      </a-button>
    </div>

    <a-modal
      v-model:visible="userProfileVisible"
      title="用户资料"
      :footer="null"
      width="400px"
    >
      <div class="user-profile">
        <div class="profile-header">
          <a-avatar :size="80" :src="selectedMember?.avatar" />
          <h2>{{ selectedMember?.nickname }}</h2>
        </div>
        <div class="profile-content">
          <div class="info-item">
            <span class="label">用户名</span>
            <span class="value">{{ selectedMember?.username }}</span>
          </div>
          <div class="info-item">
            <span class="label">群昵称</span>
            <span class="value">{{ selectedMember?.nickname }}</span>
          </div>
          <div class="info-item">
            <span class="label">群身份</span>
            <span class="value">{{ getMemberRole(selectedMember?.role) }}</span>
          </div>
          <div class="info-item">
            <span class="label">加入时间</span>
            <span class="value">{{
              formatJoinTime(selectedMember?.joinTime)
            }}</span>
          </div>
          <div class="info-item">
            <span class="label">状态</span>
            <span class="value">{{
              getMemberStatus(selectedMember?.status)
            }}</span>
          </div>
        </div>
      </div>
    </a-modal>
  </a-layout-content>
</template>

<script lang="ts" setup>
import {
  ref,
  onMounted,
  onUnmounted,
  defineProps,
  defineEmits,
  nextTick,
  computed,
  watch,
} from "vue";
import {
  SmileOutlined,
  PictureOutlined,
  PaperClipOutlined,
  FileOutlined,
  EllipsisOutlined,
  UserOutlined,
  StopOutlined,
  DeleteOutlined,
  PlusOutlined,
  DownloadOutlined,
  FileImageOutlined,
  FileWordOutlined,
  FileExcelOutlined,
  FilePdfOutlined,
  FileTextOutlined,
} from "@ant-design/icons-vue";
import { ChatGroup } from "@/types/contact";
import { useAuthStore } from "@/store/auth";
import { wsClient } from "@/util/websocket";
import {
  GroupMessage,
  MessageType,
  MessageStatus,
  ContentType,
} from "@/types/message";
import { message } from "ant-design-vue";
import { getGroupMessageHistory } from "@/api/message";
import { getGroupMembersApi } from "@/api/group";
import dayjs from "dayjs";
import EmojiPicker from "./EmojiPicker.vue";
import { uploadFile } from "@/api/message";
import { API_BASE_URL } from "@/config";
import {
  muteMemberApi,
  unmuteMemberApi,
  kickMemberApi,
  updateGroupInfoApi,
  dissolveGroupApi,
  quitGroupApi,
  updateMemberNicknameApi,
} from "@/api/group";
import { Form, Modal } from "ant-design-vue";

interface Props {
  chatInfo: ChatGroup;
}

const props = defineProps<Props>();
const inputMessage = ref("");
const authStore = useAuthStore();
const messages = ref<GroupMessage[]>([]);
const messagesContainer = ref<HTMLElement | null>(null);
const fileInput = ref<HTMLInputElement | null>(null);
const showEmojiPicker = ref(false);
const memberCount = ref(0);
const openGroupInfo = ref<boolean>(false);

// 定义群成员类型
interface GroupMember {
  userId: number;
  username: string;
  nickname: string;
  avatar: string;
  role: number;
  status: number;
  joinTime?: string;
}

// 修改群成员存储方式
const groupMembers = ref<Map<number, GroupMember>>(new Map());

const currentUserId = computed(() => authStore.user?.id);
console.log("Current user ID:", currentUserId.value);

// 获取发送者头像
const getSenderAvatar = (senderId: number) => {
  const member = groupMembers.value.get(senderId);
  return member?.avatar || "default-avatar.png";
};

// 获取发送者昵称
const getSenderName = (senderId: number) => {
  const member = groupMembers.value.get(senderId);
  return member?.nickname || "未知用户";
};

// 格式化时间
const formatTime = (time: string | undefined) => {
  if (!time) return "";
  return dayjs(time).format("HH:mm");
};

// 处理收到的消息
const handleMessage = (msg: GroupMessage) => {
  console.log("GroupChatPanel received message:", msg);
  if (!msg) return;

  console.log("Current group ID:", props.chatInfo.id);
  console.log("Message group ID:", msg.groupId);
  console.log("Message sender ID:", msg.senderId);
  console.log("Current user ID:", currentUserId.value);

  if (msg.groupId === props.chatInfo.id) {
    // 如果是文件消息，确保包含所有必要的文件信息
    if (msg.type === ContentType.FILE) {
      msg = {
        ...msg,
        fileName: extractFileName(msg.content) || "未知文件",
        fileSize: msg.fileSize || 0,
        content: msg.content, // 保持原始的文件路径
      };
      console.log("Processed file message:", msg);
    }

    // 避免重复消息
    const isDuplicate = messages.value.some(
      (m) =>
        m.senderId === msg.senderId &&
        m.content === msg.content &&
        m.createTime === msg.createTime
    );

    if (!isDuplicate) {
      console.log("Adding new message to chat:", msg);
      messages.value.push(msg);
      nextTick(() => {
        scrollToBottom();
      });
    } else {
      console.log("Duplicate message detected, ignoring");
    }
  }
};

// 添加提取文件名的辅助函数
const extractFileName = (content: string) => {
  if (!content) return null;
  const urlParts = content.split("/");
  return decodeURIComponent(urlParts[urlParts.length - 1]);
};

// 发送消息
const sendMessage = async () => {
  // 检查当前用户是否被禁言
  const currentMember = groupMembers.value.get(currentUserId.value!);
  if (currentMember?.status === 2) {
    // status 2 表示被禁言
    message.error("您已被禁言，无法发送消息");
    return;
  }

  if (currentMember?.status === 0) {
    // status 0 表示已退出
    message.error("您已退出群聊，无法发送消息");
    return;
  }

  if (!wsClient.isConnected()) {
    console.log("WebSocket disconnected, attempting to reconnect...");
    wsClient.connect();
    message.error("连接已断开，正在重新连接...");
    return;
  }

  if (!inputMessage.value.trim()) {
    return;
  }

  const msg: GroupMessage = {
    id: Date.now(),
    senderId: currentUserId.value!,
    groupId: props.chatInfo.id,
    content: inputMessage.value,
    messageType: MessageType.GROUP,
    contentType: ContentType.TEXT,
    status: MessageStatus.SENT,
    createTime: new Date().toISOString(),
  };

  try {
    wsClient.sendMessage(msg);
    messages.value.push(msg);
    inputMessage.value = "";
    await nextTick();
    scrollToBottom();
  } catch (error) {
    console.error("Failed to send message:", error);
    message.error("发送消息失败");
  }
};

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
    }
  });
};

// 加载群成员信息
const loadGroupMembers = async () => {
  try {
    const response = await getGroupMembersApi(props.chatInfo.id);
    if (response.data.code === 200) {
      memberCount.value = response.data.data.length;
      // 清空并重新填充群成员Map
      groupMembers.value.clear();
      response.data.data.forEach((member: GroupMember) => {
        groupMembers.value.set(member.userId, member);
        console.info("~~~~~~~~~~~~" + groupMembers.value);
      });
    }
  } catch (error) {
    console.error("加载群成员失败:", error);
    message.error("加载群成员失败");
  }
};

// 加载历史消息
const loadHistoryMessages = async () => {
  try {
    const response = await getGroupMessageHistory(props.chatInfo.id);
    if (response.data.code === 200) {
      // 处理历史消息中的文件消息
      console.log("History messages:", response.data.data);
      messages.value = response.data.data.map((msg: GroupMessage) => {
        if (msg.type === ContentType.FILE) {
          // 从文件URL中提取文件名
          const urlParts = msg.content.split("/");
          const fullFileName = urlParts[urlParts.length - 1];
          // 解码文件名（处理可能的URL编码）
          const decodedFileName = decodeURIComponent(fullFileName);

          return {
            ...msg,
            fileName: decodedFileName,
            fileSize: 0, // 由于历史消息中没有文件大小，设为0
          };
        }
        return msg;
      });
      scrollToBottom();
    }
  } catch (error) {
    console.error("加载历史消息失败:", error);
    message.error("加载历史消息失败");
  }
};

const showDrawerWithGroupInfo = () => {
  openGroupInfo.value = true;
};

// 添加对 chatInfo 的监听
watch(
  () => props.chatInfo,
  async (newGroup) => {
    if (newGroup) {
      messages.value = []; // 清空当前消息
      await Promise.all([
        loadGroupMembers(), // 加载群成员信息
        loadHistoryMessages(), // 加载历史消息
      ]);
    }
  },
  { immediate: true }
);

// 确保件加载时获取群员信息
onMounted(async () => {
  console.log("GroupChatPanel mounted");
  console.log("Current WebSocket status:", wsClient.isConnected());

  // 确保 WebSocket 连接
  if (!wsClient.isConnected()) {
    console.log("Connecting WebSocket...");
    await wsClient.connect();
  }

  wsClient.addMessageHandler(MessageType.GROUP, handleMessage);

  await loadGroupMembers();
});

onUnmounted(() => {
  console.log("Removing message handler for type:", MessageType.GROUP);
  wsClient.removeMessageHandler(MessageType.GROUP, handleMessage);
});

const insertEmoji = (emoji: string) => {
  inputMessage.value += emoji;
};

const handleFileSelect = async (event: Event) => {
  const files = (event.target as HTMLInputElement).files;
  if (!files || files.length === 0) return;

  const file = files[0];
  const maxSize = 10 * 1024 * 1024;

  if (file.size > maxSize) {
    message.error("文件大小不能超过10MB");
    return;
  }

  try {
    const formData = new FormData();
    formData.append("file", file);
    formData.append("senderId", currentUserId.value!.toString());
    formData.append("groupId", props.chatInfo.id.toString());
    formData.append("messageType", MessageType.GROUP.toString());

    const response = await uploadFile(formData, MessageType.GROUP);
    const result = response.data;

    if (result.code === 200) {
      // 构建文件消息
      const msg: GroupMessage = {
        id: Date.now(),
        senderId: currentUserId.value!,
        groupId: props.chatInfo.id,
        content: result.data.url,
        messageType: MessageType.GROUP,
        contentType: ContentType.FILE,
        status: MessageStatus.SENT,
        createTime: new Date().toISOString(),
        fileName: file.name, // 使用原始文件名
        fileSize: file.size,
      };

      console.log("Sending file message:", msg);
      wsClient.sendMessage(msg);
      messages.value.push(msg);
      scrollToBottom();
    }
  } catch (error) {
    message.error("文件发送失败");
    console.error("文件发送失败:", error);
  } finally {
    // 清空文件输入框
    if (fileInput.value) {
      fileInput.value.value = "";
    }
  }
};

const handleFileClick = () => {
  fileInput.value?.click();
};

const renderMessage = (message: GroupMessage) => {
  if (message.contentType === ContentType.FILE) {
    console.log("Rendering file message:", message);
    const fileUrl = `${API_BASE_URL}/file${message.content}`;
    const fileName = message.fileName || "未知文件";
    const fileSize = message.fileSize
      ? formatFileSize(message.fileSize)
      : "未知大小";

    // 获取文件扩展名
    const fileExt = fileName.split(".").pop()?.toLowerCase() || "";

    // 根据文件类型选择图标
    let fileIcon = "file";
    if (["jpg", "jpeg", "png", "gif"].includes(fileExt)) {
      fileIcon = "file-image";
    } else if (["doc", "docx"].includes(fileExt)) {
      fileIcon = "file-word";
    } else if (["xls", "xlsx"].includes(fileExt)) {
      fileIcon = "file-excel";
    } else if (["pdf"].includes(fileExt)) {
      fileIcon = "file-pdf";
    } else if (["txt"].includes(fileExt)) {
      fileIcon = "file-text";
    }

    return `
      <a href="${fileUrl}" class="file-message-wrapper" target="_blank" download="${fileName}">
        <div class="file-icon">
          <i class="anticon anticon-${fileIcon}"></i>
          <span class="file-ext">${fileExt.toUpperCase()}</span>
        </div>
        <div class="file-info">
          <div class="file-name" title="${fileName}">${fileName}</div>
          <div class="file-size">${fileSize}</div>
        </div>
        <div class="download-button">
          <i class="anticon anticon-download"></i>
        </div>
      </a>
    `;
  }
  return message.content;
};

const formatFileSize = (bytes: number) => {
  if (bytes === 0) return "0 B";
  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
};

const memberContextMenuVisible = ref(false);
const selectedMember = ref<GroupMember | null>(null);

// 判断当前户是否是管理员
const isGroupAdmin = computed(() => {
  const currentMember = groupMembers.value.get(currentUserId.value!);
  console.log("Current member:", currentMember);
  if (
    // role 1 是管理员，role 2 是群主
    currentMember?.role !== 0 &&
    currentMember?.userId !== selectedMember.value?.userId
  ) {
    return true;
  } else {
    return false;
  }
});

// 处理成员菜单可见性变化
const handleMemberContextMenuVisibleChange = (
  visible: boolean,
  member: GroupMember
) => {
  if (visible) {
    selectedMember.value = member;
  }
  memberContextMenuVisible.value = visible;
};

// 处理成员菜单点击
const handleMemberMenuClick = async ({ key }: { key: string }) => {
  if (!selectedMember.value) return;

  memberContextMenuVisible.value = false;

  switch (key) {
    case "profile":
      userProfileVisible.value = true;
      break;
    case "muteORunmute":
      if (selectedMember.value.status === 1) {
        try {
          await muteMemberApi(
            props.chatInfo.id,
            currentUserId.value!,
            selectedMember.value.userId,
            3600
          );
          // 更新成员状态为禁言
          const member = groupMembers.value.get(selectedMember.value.userId);
          if (member) {
            member.status = 2;
            groupMembers.value.set(selectedMember.value.userId, member);
          }
          message.success("操作成功");
        } catch (error) {
          message.error("操作失败");
        }
      } else if (selectedMember.value.status === 2) {
        try {
          await unmuteMemberApi(
            props.chatInfo.id,
            currentUserId.value!,
            selectedMember.value.userId
          );
          // 更新成员状态为正常
          const member = groupMembers.value.get(selectedMember.value.userId);
          if (member) {
            member.status = 1;
            groupMembers.value.set(selectedMember.value.userId, member);
          }
          message.success("操作成功");
        } catch (error) {
          message.error("操作失败");
        }
      }
      break;
    case "remove":
      try {
        await kickMemberApi(
          props.chatInfo.id,
          currentUserId.value!,
          selectedMember.value.userId
        );
        message.success("已将该员移出群聊");
        await loadGroupMembers(); // 重新加载群成员列表
      } catch (error) {
        message.error("操作失败");
      }
      break;
  }
};

// 获取弹出容器
const getPopupContainer = (triggerNode: HTMLElement) =>
  triggerNode.parentNode as HTMLElement;

// 显示确认对话框
const showConfirmDialog = (title: string, content: string) => {
  return new Promise<boolean>((resolve) => {
    Modal.confirm({
      title,
      content,
      onOk: () => resolve(true),
      onCancel: () => resolve(false),
    });
  });
};

// 添加用户资料相关的状态
const userProfileVisible = ref(false);

// 获取成员角色描述
const getMemberRole = (role?: number) => {
  switch (role) {
    case 2:
      return "群主";
    case 1:
      return "管理员";
    case 0:
    default:
      return "普通成员";
  }
};

// 格式化加入时间
const formatJoinTime = (time?: string) => {
  if (!time) return "未知";
  return dayjs(time).format("YYYY-MM-DD HH:mm");
};

// 获取成员状态
const getMemberStatus = (status?: number) => {
  switch (status) {
    case 1:
      return "正常";
    case 2:
      return "已禁言";
    case 0:
    default:
      return "未知";
  }
};

// 判断是否是群主
const isGroupOwner = computed(() => {
  const currentMember = groupMembers.value.get(currentUserId.value!);
  return currentMember?.role === 2;
});

// 群资料表单相关
const modifyGroupInfoVisible = ref(false);
const groupInfoFormRef = ref();
const groupInfoForm = ref({
  avatar: props.chatInfo?.avatar || "",
  name: props.chatInfo?.name || "",
  announcement: props.chatInfo?.announcement || "",
  description: props.chatInfo?.description || "",
});

const groupInfoRules = {
  name: [{ required: true, message: "请输入群名称", trigger: "blur" }],
};

// 群昵称表单相关
const modifyNicknameVisible = ref(false);
const nicknameForm = ref({
  nickname: "",
});

// 显示修改群资料弹窗
const showModifyGroupInfo = () => {
  groupInfoForm.value = {
    avatar: props.chatInfo?.avatar || "",
    name: props.chatInfo?.name || "",
    announcement: props.chatInfo?.announcement || "",
    description: props.chatInfo?.description || "",
  };
  modifyGroupInfoVisible.value = true;
};

// 显示修改昵称弹窗
const showModifyNickname = () => {
  const currentMember = groupMembers.value.get(currentUserId.value!);
  nicknameForm.value.nickname = currentMember?.nickname || "";
  modifyNicknameVisible.value = true;
};

// 头像上传前的校验
const beforeAvatarUpload = (file: File) => {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJpgOrPng) {
    message.error("只能上传 JPG/PNG 格式的图片！");
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error("图片大小不能超过 2MB！");
    return false;
  }
  return true;
};

// 处理头像变更
const handleAvatarChange = (info: any) => {
  if (info.file.status === "uploading") {
    return;
  }
  if (info.file.status === "done") {
    // 这里需要根据实际的上传接口返回值来设置
    groupInfoForm.value.avatar = info.file.response.url;
  }
};

// 取消修改群资料
const handleModifyGroupInfoCancel = () => {
  modifyGroupInfoVisible.value = false;
  groupInfoFormRef.value?.resetFields();
};

// 添加本地状态来存储群信息
const localGroupInfo = ref({
  avatar: "",
  name: "",
  announcement: "",
  description: "",
  id: 0,
});

// 监听 chatInfo 的变化
watch(
  () => props.chatInfo,
  (newValue) => {
    if (newValue) {
      localGroupInfo.value = {
        id: newValue.id,
        name: newValue.name,
        avatar: newValue.avatar,
        announcement: newValue.announcement || "",
        description: newValue.description || "",
      };
    }
  },
  { immediate: true, deep: true }
);

// 修改提交群资料的函数
const handleModifyGroupInfoSubmit = async () => {
  try {
    await groupInfoFormRef.value?.validate();
    const response = await updateGroupInfoApi(
      props.chatInfo.id,
      groupInfoForm.value
    );
    if (response.data.code === 200) {
      message.success("修改成功");
      modifyGroupInfoVisible.value = false;

      // 更新本地状态
      localGroupInfo.value = {
        ...localGroupInfo.value,
        avatar: groupInfoForm.value.avatar,
        name: groupInfoForm.value.name,
        announcement: groupInfoForm.value.announcement,
        description: groupInfoForm.value.description,
      };

      // 通知父组件更新
      emit("updateGroupInfo", {
        id: props.chatInfo.id,
        avatar: groupInfoForm.value.avatar,
        name: groupInfoForm.value.name,
        announcement: groupInfoForm.value.announcement,
        description: groupInfoForm.value.description,
      });
    }
  } catch (error) {
    message.error("修改失败");
  }
};

// 提交修改昵称
const handleModifyNicknameSubmit = async () => {
  try {
    const response = await updateMemberNicknameApi(
      props.chatInfo.id,
      currentUserId.value!,
      nicknameForm.value.nickname
    );
    if (response.data.code === 200) {
      message.success("修改成功");
      modifyNicknameVisible.value = false;
      // 更新本地成员信息
      const member = groupMembers.value.get(currentUserId.value!);
      if (member) {
        member.nickname = nicknameForm.value.nickname;
        groupMembers.value.set(currentUserId.value!, member);
      }
    }
  } catch (error) {
    message.error("修改失败");
  }
};

// 解散群聊
const dissolveGroup = async () => {
  try {
    const confirmed = await showConfirmDialog(
      "解散群聊",
      "确定要解散该群聊吗？此操作不可恢复。"
    );
    if (confirmed) {
      const response = await dissolveGroupApi(
        props.chatInfo.id,
        currentUserId.value!
      );
      if (response.data.code === 200) {
        message.success("群聊已解散");
        // 这里需要触发一个事件通知父组件更新群聊列表
        emit("groupDissolved", props.chatInfo.id);
      }
    }
  } catch (error) {
    message.error("操作失败");
  }
};

// 退出群聊
const quitGroup = async () => {
  try {
    const confirmed = await showConfirmDialog(
      "退出群聊",
      "确定要退出该群聊吗？"
    );
    if (confirmed) {
      const response = await quitGroupApi(
        props.chatInfo.id,
        currentUserId.value!
      );
      if (response.data.code === 200) {
        message.success("已退出群聊");
        // 这里需要触发一个事件通知父组件更新群聊列表
        emit("groupQuitted", props.chatInfo.id);
      }
    }
  } catch (error) {
    message.error("操作失败");
  }
};

const emit = defineEmits(["groupDissolved", "groupQuitted", "updateGroupInfo"]);
</script>

<style scoped>
.chat-panel {
  display: flex;
  flex-direction: column;
  background: #fff;
  height: 100%;
}

.chat-header {
  height: 64px;
  line-height: 64px;
  padding: 0 24px;
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
}

.chat-title {
  font-size: 16px;
  font-weight: 500;
}

.chat-groupInfo {
  height: 50px;
  width: 50px;
}

.member-count {
  font-size: 14px;
  color: #999;
  margin-left: 8px;
}

.chat-messages {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
  background: #f5f5f5;
}

.message {
  display: flex;
  align-items: flex-start;
  margin-bottom: 24px;
  gap: 12px;
}

.message-self {
  flex-direction: row-reverse;
}

.message-wrapper {
  display: flex;
  flex-direction: column;
  max-width: 70%;
}

.message-sender {
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}

.message-content {
  padding: 12px 16px;
  background: #fff;
  border-radius: 8px;
  word-break: break-all;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  display: inline-block;
  max-width: 100%;
}

.message-self .message-content {
  background: #1890ff;
  color: #fff;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  text-align: right;
}

.chat-input-area {
  padding: 16px 24px;
  background: #fff;
  border-top: 1px solid #f0f0f0;
  position: relative;
}

.chat-toolbar {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 12px;
  color: #595959;
}

.toolbar-icon {
  font-size: 20px;
  cursor: pointer;
  transition: color 0.3s;
}

.toolbar-icon:hover {
  color: #1890ff;
}

.chat-input {
  margin-bottom: 12px;
  resize: none;
  border-radius: 4px;
}

.chat-input:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.send-button {
  float: right;
  height: 32px;
  padding: 0 16px;
}

.emoji-picker {
  position: absolute;
  bottom: 200px;
  left: 24px;
  width: 300px;
  height: 200px;
  background: #fff;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  z-index: 1000;
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f5f5f5;
}

/* 头像样式 */
.message :deep(.ant-avatar) {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  flex-shrink: 0;
}

/* 输入框样式 */
.chat-input-area :deep(.ant-input) {
  border-radius: 4px;
  resize: none;
}

/* 按钮 */
.chat-input-area :deep(.ant-btn) {
  border-radius: 4px;
}

/* 确保表情选择器和其他图标对齐 */
:deep(.emoji-picker) {
  display: flex;
  align-items: center;
  padding: 0 8px;
}

.file-message {
  display: flex;
  align-items: center;
  gap: 8px;
}

.file-message .anticon {
  font-size: 16px;
}

.file-message a {
  color: #1890ff;
  text-decoration: none;
}

.file-message a:hover {
  text-decoration: underline;
}

.file-size {
  font-size: 12px;
  color: #999;
}

.group-info-container {
  padding: 16px 0;
}

.group-basic-info {
  text-align: center;
  padding: 16px 0;
}

.group-avatar {
  margin-bottom: 16px;
}

.group-avatar :deep(.ant-avatar) {
  border: 2px solid #f0f0f0;
  padding: 4px;
  background: #fff;
  transition: transform 0.3s ease;
}

.group-avatar :deep(.ant-avatar):hover {
  transform: scale(1.05);
}

.group-basic-info h3 {
  margin-bottom: 8px;
  font-size: 18px;
  font-weight: 500;
}

.group-id {
  color: #999;
  font-size: 14px;
}

.group-announcement {
  padding: 0 16px;
}

.group-announcement h4 {
  margin-bottom: 12px;
  font-weight: 500;
}

.members-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 16px;
  margin-bottom: 16px;
}

.members-list {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  padding: 0 16px;
}

.member-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.member-item span {
  font-size: 12px;
  color: #666;
}

.add-member {
  cursor: pointer;
}

.group-actions {
  padding: 16px;
}

.action-btn {
  margin-bottom: 12px;
}

.action-btn:last-child {
  margin-bottom: 0;
}

/* 右键菜单样式 */
:deep(.ant-dropdown-menu) {
  min-width: 160px;
}

:deep(.ant-dropdown) {
  z-index: 1050;
}

:deep(.ant-dropdown-menu-item) {
  padding: 8px 16px;
}

:deep(.ant-dropdown-menu-item .anticon) {
  margin-right: 8px;
}

/* 用户资料样式 */
.user-profile {
  padding: 20px;
}

.profile-header {
  text-align: center;
  margin-bottom: 24px;
}

.profile-header h2 {
  margin-top: 12px;
  font-size: 18px;
  color: #333;
}

.profile-content {
  background: #f8f8f8;
  border-radius: 8px;
  padding: 16px;
}

.info-item {
  display: flex;
  margin-bottom: 12px;
  padding: 8px;
  background: #fff;
  border-radius: 4px;
}

.info-item .label {
  width: 80px;
  color: #666;
}

.info-item .value {
  flex: 1;
  color: #333;
}

.modify-group-info {
  display: flex;
  gap: 24px;
  padding: 20px;
}

.group-avatar-section {
  flex: 0 0 120px;
}

.group-form-section {
  flex: 1;
}

.avatar-uploader {
  width: 120px;
  height: 120px;
}

a {
  color: #000000;
}

:deep(.avatar-uploader .ant-upload) {
  width: 120px;
  height: 120px;
}

:deep(.avatar-uploader .ant-upload img) {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.form-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 文件消息样式 */
.file-message-wrapper {
  display: flex;
  align-items: center;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 12px;
  max-width: 320px;
  transition: all 0.3s ease;
}

.message-self .file-message-wrapper {
  background: #e6f7ff;
  border-color: #91d5ff;
}

.file-message-wrapper:hover {
  background: #fff;
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.file-icon {
  position: relative;
  width: 40px;
  height: 40px;
  background: #e6f7ff;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  flex-shrink: 0;
}

.file-icon .anticon {
  font-size: 20px;
  color: #1890ff;
}

.file-ext {
  position: absolute;
  bottom: -2px;
  font-size: 8px;
  background: #1890ff;
  color: white;
  padding: 1px 4px;
  border-radius: 4px;
  text-transform: uppercase;
}

.file-info {
  flex: 1;
  min-width: 0;
  margin-right: 12px;
}

.file-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.file-size {
  font-size: 12px;
  color: #666;
}

.download-button {
  width: 32px;
  height: 32px;
  background: #1890ff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  transition: all 0.3s ease;
  flex-shrink: 0;
}

.download-button:hover {
  background: #40a9ff;
  transform: scale(1.1);
}

.download-button .anticon {
  font-size: 16px;
  color: white;
}

/* 确保消息内容区域可以容纳文件消息 */
.message-content:has(.file-message-wrapper) {
  min-width: 240px;
  max-width: 400px;
}

/* 调整自己发送的文件消息样式 */
.message-self .file-message-wrapper {
  background: #e6f7ff;
  border-color: #91d5ff;
}

.message-self .file-icon {
  background: #fff;
}
</style>
